package cn.itcast.controller.aop;

import cn.itcast.domain.SysLog;
import cn.itcast.domain.User;
import cn.itcast.service.log.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class LogManager {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private HttpSession session;
    @Autowired
    private HttpServletRequest request;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        SysLog sysLog = new SysLog();
        sysLog.setId(UUID.randomUUID().toString());
        sysLog.setTime(new Date());
        User user =(User)session.getAttribute("loginUser");
        sysLog.setCompanyId(user.getCompanyId());
        sysLog.setCompanyName(user.getCompanyName());
        sysLog.setUserName(user.getUserName());
        sysLog.setIp(request.getRemoteAddr());

        MethodSignature signature =(MethodSignature)pjp.getSignature();
        Method method = signature.getMethod();
        RequestMapping annotation = method.getAnnotation(RequestMapping.class);
        sysLog.setMethod(method.getName());   //方法名
        sysLog.setAction(annotation.name());  //注解里面的name属性描述
        sysLogService.save(sysLog); //在所有controller下的原方法执行之前调用：保存一条日志
        return pjp.proceed();
    }
}
